(function (factory) {
    if (typeof define === 'function' && define.amd !== undefined) {
        // AMD模式
        define('tailoring2.0', ['jquery', 'hammer', 'tom.plugin', 'tom.lib', 'hammer.fake', 'hammer.showtouch'], function (require) {
            var $ = require('jquery');
            var hammer = require('hammer');
            require('tom.plugin');
            var tomLib = require('tom.lib');
            return factory($, hammer, tomLib);
        });
    } else {
        // 全局模式
        factory($, window.Hammer, window.tomLib);
    }
})(function ($, hammer, tomLib) {
    function Tailoring() {
        var that = this;
        that.previewStyle = {
            x: 0,
            y: 0,
            scale: 1,
            rotate: 0,
            ratio: 1
        };
        that.rotate = 0;
        that.flag = false;
        that.init();
    }
    Tailoring.prototype = {
        init: function () {
            var that = this;
            var domStr;
            if (!that.dom) {
                domStr = '<div class="app" id="uploadPage">' +
                    '<div class="upload-loading">' +
                    '<div class="loadEffect">' +
                    '<span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span>' +
                    '</div>' +
                    '</div >' +
                    '<div class="bar">' +
                    '<a class="back pull-left" id="closeCrop">返回</a>' +
                    '<a href="javascript:void(0)" class="shu toggle active"></a>' +
                    '<a href="javascript:void(0)" class="heng toggle"></a>' +
                    '<a id="getFile" class="pull-right">使用</a></div>' +
                    '<div class="main">' +
                    '<canvas class="upload-mask"></canvas>' +
                    '<div class="preview-box">' +
                    '<img id="preview" />' +
                    '</div>' +
                    '<canvas class="photo-canvas"></canvas>' +
                    '<a id="rotateBtn">旋转图片</a>' +
                    '</div>' +
                    '</div >';
                that.dom = $(domStr);
                $(document.body).append(that.dom);
            }
            that.transform = tomLib.prefixStyle('transform');
            that.$rotateBtn = $('#rotateBtn');
            that.$getFile = $('#getFile');
            that.$preview = $('#preview');
            that.$uploadPage = $('#uploadPage');
            that.$mask = $('.upload-mask');
            that.$loading = $('.upload-loading');
            that.maskCtx = that.$mask[0].getContext('2d');
            that.imgData = '';
            var $doc = $(document);
            $doc.on('scroll', function (e) {
                if (that.flag) {
                    e.preventDefault();
                }
            });

            // that.$file.on('click', function () {
            //     setTimeout(function () {
            //         that.resetUserOpts();
            //     }, 1000);
            // });

            $('.photo-canvas').hammer({
                gestureCb: function (o) {
                    // 每次缩放拖拽的回调
                    $.extend(that.previewStyle, o);
                    that.$preview.css(that.transform, 'translate3d(' + that.previewStyle.x + 'px,' + that.previewStyle.y + 'px,0) rotate(' + that.rotate + 'deg) scale(' + that.previewStyle.scale / that.previewStyle.ratio + ')');
                }
            });

            // 旋转图片
            that.$rotateBtn.on('click', function () {
                that.rotate += 90;
                if (that.rotate >= 360) {
                    that.rotate -= 360;
                }
                $('.photo-canvas').hammer('setRotate', that.rotate);
                that.myCrop.setCropStyle(that.previewStyle);
                that.$preview.css(that.transform, 'translate3d(' + that.previewStyle.x + 'px,' + that.previewStyle.y + 'px,0) rotate(' + that.rotate + 'deg) scale(' + that.previewStyle.scale / that.previewStyle.ratio + ')');
            });

            // 获取图片并关闭弹窗返回到表单界面
            that.$getFile.on('click', function () {
                that.$uploadPage.hide();
                if (!tomLib.img) return;
                that.previewStyle.rotate = that.rotate;
                var cropInfo;
                that.myCrop.setCropStyle(that.previewStyle);
                // 自定义getCropFile({type:'png',background:'red',lowDpi:true})
                cropInfo = that.myCrop.getCropFile({});
                that.opts.callback && that.opts.callback(cropInfo.src);
                tomLib.img = null;
                // 阻止页面滚动
                that.flag = false;
            });

            // 关闭弹窗按钮
            $('#closeCrop').on('click', function () {
                that.$uploadPage.hide();
                that.resetUserOpts();
                that.myCrop.setCropStyle(that.previewStyle);
                that.flag = false;
                // file input控件对于选择同一个文件不会再触发onchange事件。
                // 导致点击返回后，再选择同一个文件不会再出现剪切功能。
                if (that.opts.type === 'inputfile') {
                    $(that.opts.bindFile).val('');
                }
            });

            // 裁剪为横竖图切换
            $('.app .toggle').on('click', function () {
                var $this = $(this);
                if (!$this.hasClass('active')) {
                    $('.app .active').removeClass('active');
                    $this.addClass('active');
                    if ($this.hasClass('shu')) {
                        tomLib.opts = $.extend(tomLib.opts, {
                            cropWidth: that.opts.cropWidth,
                            cropHeight: that.opts.cropHeight
                        });
                    } else {
                        tomLib.opts = $.extend(tomLib.opts, {
                            cropWidth: that.opts.cropHeight,
                            cropHeight: that.opts.cropWidth
                        });
                    }
                    that.resetUserOpts();
                    tomLib.updateCanvas(tomLib.opts);
                    tomLib.showCropModal(that.$uploadPage, that.$mask, that.maskCtx, tomLib.opts);
                }
            });
        },

        /**
         * 重新设定
         */
        resetUserOpts: function () {
            var that = this;
            $('.photo-canvas').hammer('reset');
            that.previewStyle = {
                scale: 1,
                x: 0,
                y: 0,
                rotate: 0
            };
            that.rotate = 0;
            that.$preview.hide();
        },
        updateTitle: function () {
            var that = this;
            var toogle = that.dom.find('.toggle');
            var text1Arr = [];
            if (that.opts.ratio) {
                text1Arr = [that.opts.ratio * that.opts.cropWidth, that.opts.ratio * that.opts.cropHeight];
            } else if (that.enableRatio && window.devicePixelRatio) {
                text1Arr = [window.devicePixelRatio * that.opts.cropWidth, window.devicePixelRatio * that.opts.cropHeight];
            } else {
                text1Arr = [window.devicePixelRatio * that.opts.cropWidth, window.devicePixelRatio * that.opts.cropHeight];
            }
            var text2Arr = text1Arr.reverse();
            toogle.eq(0).text(text1Arr.join('*'));
            toogle.eq(1).text(text2Arr.join('*'));
        },

        /**
         * 更新配置
         * @param {any} ops
         */
        config: function (ops) {
            var that = this;
            that.opts = {
                // 绑定Input file
                bindFile: '#file',
                // 上传类型 inputfile imgsrc
                type: 'inputfile',
                // 是否启用高清,高清得到的图片会比较大
                enableRatio: true,
                // 是否自定义图片比例
                ratio: '',
                // 放一个canvas对象
                canvas: $('.photo-canvas')[0],
                // 剪切大小
                cropWidth: 200,
                cropHeight: 300,
                // 绑定一个预览的img标签
                bindPreview: that.$preview,
                // 是否使用hammer手势，否的话将不支持缩放
                useHammer: true,
                oninit: function () {

                },
                onChange: function () {
                    that.resetUserOpts();
                    tomLib.showCropModal(that.$uploadPage, that.$mask, that.maskCtx, tomLib.opts);
                    that.$loading.show();
                    that.flag = true;
                },
                // 用户每次选择图片后执行回调
                onLoad: function (data) {
                    that.imgData = data;
                    that.previewStyle.ratio = that.imgData.ratio;
                    that.$preview.attr('src', that.imgData.originSrc).css({
                        width: that.imgData.width,
                        height: that.imgData.height
                    }).css(that.transform, 'scale(' + 1 / that.previewStyle.ratio + ')');
                    setTimeout(function () {
                        that.$preview.show();
                    }, 100);
                    that.myCrop.setCropStyle(that.previewStyle);
                    that.$loading.hide();
                }
            };
            that.opts = $.extend(that.opts, ops);
            that.updateTitle();
            // 插件调用主体
            that.myCrop = tomLib.cropImage(that.opts);
        }
    };
    window.Tailoring = Tailoring;
    return Tailoring;
});